﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using acessaDB;
using System.Data;
using Microsoft.Reporting.WebForms;

namespace Frame
{

    public class GerarPDF
    {
        acessaDB.conectaDBFireBird fireBird = new conectaDBFireBird();
        string conectionString = System.Configuration.ConfigurationManager.AppSettings["SQLServerConnectionLocal"];
        //MONTAR SUBREPORT
        string dsNameSubReport = string.Empty;
        DataTable dtSubReport = new DataTable();

        public GerarPDF()
        {
            if (System.Configuration.ConfigurationManager.AppSettings["ambiente"] == "PROD")
                conectionString = System.Configuration.ConfigurationManager.AppSettings["SQLServerConnectionProd"];
        }

        /// <summary>
        /// Exportar documentos Reportviewr .RDLC para .PDF
        /// </summary>
        public string _exportarReportViewerPDF(     string strSQL,
                                                    string nomeCaminho,
                                                    string nomeRelatorio,
                                                    string varSessionPathFile,
                                                    string indicadorRelatorio,
                                                    string dataSetName,
                                                    string[] parametros = null

                                                )
        {

            ReportViewer report = new ReportViewer();
            string result = string.Empty;
            try
            {

                System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(strSQL, conectionString);
                DataSet ds = new DataSet();
                adapter.Fill(ds, dataSetName);

                ReportDataSource rptSource = new ReportDataSource(dataSetName, ds.Tables[0]);
                report.LocalReport.DataSources.Add(rptSource);                
                report.LocalReport.ReportPath = (nomeCaminho + nomeRelatorio + ".rdlc");
                report.LocalReport.ReportEmbeddedResource = (nomeRelatorio + ".rdlc");
                if (parametros != null)
                {
                    foreach (string p in parametros)
                    {
                        ReportParameter param = new ReportParameter();
                        param.Name = p.Substring(0,p.LastIndexOf("="));
                        param.Values.Add(p.Substring(p.LastIndexOf("=")+1));
                        report.LocalReport.SetParameters(param);
                    }

                }

                Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding = string.Empty;
                string extension = string.Empty;
                string fileNameExtension;

                byte[] exportBytes = report.LocalReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings);                
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = mimeType;
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedReport." + fileNameExtension);
                HttpContext.Current.Response.BinaryWrite(exportBytes);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();

                return nomeCaminho + nomeRelatorio + ".pdf";
            }

            catch (Exception ex)
            {
                report.Dispose();
                result = ex.ToString();

            }

            return result;

        }


        public string _exportarReportViewerPDF( 
                                                string nomeCaminho,
                                                string nomeRelatorio,                                                
                                                string indicadorRelatorio
                                                

                                                )
        {

            ReportViewer report = new ReportViewer();
            try
            {
                
                report.LocalReport.ReportPath = (nomeCaminho + nomeRelatorio + ".rdlc");
                report.LocalReport.ReportEmbeddedResource = (nomeRelatorio + ".rdlc");

                Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding = string.Empty;
                string extension = string.Empty;
                string fileNameExtension;

                byte[] exportBytes = report.LocalReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = mimeType;
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedReport." + fileNameExtension);
                HttpContext.Current.Response.BinaryWrite(exportBytes);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();

                return nomeCaminho + nomeRelatorio + ".pdf";
            }

            catch (Exception ex)
            {
                report.Dispose();
                string error = ex.ToString();

            }

            return null;

        }

        public string _exportarReportViewerPDF(
                                                        Page page,
                                                        string strSQL,
                                                        string nomeCaminho,
                                                        string nomeRelatorio,
                                                        string dataSetName,
                                                        string strSQLHeader = "",
                                                        string dataSetNameHeader = "",
                                                        string sqlSubReport = "",
                                                        string dataSetSubReport = ""
                                                    )
        {

            ReportViewer report = new ReportViewer();
            try
            {

                DataSet dsReport = fireBird.retornaDataSet(strSQL, conectionString);
                ReportDataSource rptSource = new ReportDataSource(dataSetName, dsReport.Tables[0]);
                report.LocalReport.DataSources.Add(rptSource);
                //CABEÇALHO DO RELATORIO
                if (!string.IsNullOrEmpty(dataSetNameHeader))
                {
                    DataSet dsHeader = fireBird.retornaDataSet(strSQLHeader, conectionString);
                    ReportDataSource rptSourceHeader = new ReportDataSource(dataSetNameHeader, dsHeader.Tables[0]);
                    report.LocalReport.DataSources.Add(rptSourceHeader);
                }
                //SUBREPORT
                if (!string.IsNullOrEmpty(dataSetSubReport))
                {
                    DataSet dsSubReport = fireBird.retornaDataSet(sqlSubReport, conectionString);
                    dtSubReport = dsSubReport.Tables[0];
                    dsNameSubReport = dataSetSubReport;
                    report.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);

                }

                report.LocalReport.ReportPath = (nomeCaminho + nomeRelatorio + ".rdlc");
                report.LocalReport.ReportEmbeddedResource = (nomeRelatorio + ".rdlc");

                Warning[] warnings;
                string[] streamids;
                string mimeType;
                string encoding = string.Empty;
                string extension = string.Empty;
                string fileNameExtension;

                byte[] exportBytes = report.LocalReport.Render("PDF", null, out mimeType, out encoding, out fileNameExtension, out streamids, out warnings);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = mimeType;
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedReport." + fileNameExtension);
                HttpContext.Current.Response.BinaryWrite(exportBytes);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();

                return nomeCaminho + nomeRelatorio + ".pdf";
            }

            catch (Exception ex)
            {
                report.Dispose();
                string error = ex.ToString();

            }

            return null;

        }

        public void LocalReport_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
        {
            e.DataSources.Add(new ReportDataSource(dsNameSubReport, dtSubReport));
        }
    }



}